package com.formiaomiao.demain.activity;

import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.formiaomiao.demain.R;
import com.formiaomiao.demain.adapter.ThemeAdapter;
import com.formiaomiao.demain.base.BaseActivity;
import com.formiaomiao.demain.base.BaseUrl;
import com.formiaomiao.demain.model.ThemeBean;
import com.formiaomiao.demain.util.CustomSDCardLoader;
import com.formiaomiao.demain.util.DownLoadFileUtils;
import com.formiaomiao.demain.util.PreferenceUtils;
import com.formiaomiao.demain.util.PreferenceValues;
import com.formiaomiao.demain.util.ToastUtils;
import com.formiaomiao.demain.weight.LoadingDialog;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import skin.support.SkinCompatManager;

public class ModifyActivity extends BaseActivity {

    @BindView(R.id.iv_class_back)
    ImageView ivClassBack;
    @BindView(R.id.tv_class_name)
    TextView tvClassName;
    @BindView(R.id.gv_theme)
    RecyclerView gvTheme;

    String SKIN_DIR;        //皮肤路径
    File skin;              //批复文件

    LoadingDialog loadingDialog;

    ThemeAdapter adapter;
    ThemeBean themeBean = new ThemeBean();
    List<ThemeBean.DataBean.ListBean> list = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_modify);
        ButterKnife.bind(this);
        ViewInit();
    }

    public void ViewInit() {
        loadingDialog = new LoadingDialog(this);
        tvClassName.setText("修改主题");
        gvTheme.setLayoutManager(new GridLayoutManager(this, 2));
        adapter = new ThemeAdapter(this, list);
        adapter.setHasStableIds(true);
        gvTheme.setAdapter(adapter);
        GetThemeInit();
        adapter.setOnItemClickListener(new ThemeAdapter.onItemClickListener() {
            @Override
            public void itemClickListener(View v, int position) {
                if (position == 0) {
                    adapter.setSelectedPosition(position);
                    adapter.notifyDataSetChanged();
                    PreferenceUtils.setString(ModifyActivity.this, PreferenceValues.SELECTTHEME, position + "");
                    // 恢复应用默认皮肤
                    SkinCompatManager.getInstance().restoreDefaultTheme();
                } else {
                    if (list.get(position).isHavefile()) {
                        SelectTheme(list.get(position).getFileName() + ".skin", position);
                    } else {
                        downloadFile(ModifyActivity.this, list.get(position).getThemeUrl(),
                                Environment.getExternalStorageDirectory() + "/demain/skin/"
                                , list.get(position).getFileName(), list.get(position).getThemeUrl(), position);
                    }
                }
            }
        });
    }

    /**
     * 获取主题
     */
    public void GetThemeInit() {
        loadingDialog.show();
        OkGo.<String>post(BaseUrl.THEMESELECT).tag(this).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (response.body().contains("200")) {
                    themeBean = gson.fromJson(response.body(), ThemeBean.class);
                    list.clear();
                    list.addAll(themeBean.getData().getList());
                    if (PreferenceUtils.getString(ModifyActivity.this, PreferenceValues.SELECTTHEME) != null &&
                            !PreferenceUtils.getString(ModifyActivity.this, PreferenceValues.SELECTTHEME).equals("")) {
                        adapter.setSelectedPosition(Integer.decode(PreferenceUtils.getString(ModifyActivity.this, PreferenceValues.SELECTTHEME)));
                    } else {
                        adapter.setSelectedPosition(0);
                    }
                    adapter.notifyDataSetChanged();
                    loadingDialog.dismiss();
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                loadingDialog.dismiss();
            }
        });
    }

    /**
     * @param context          上下文
     * @param fileUrl          下载完整url
     * @param destFileDir      SD路径
     * @param destFileName     文件名
     * @param mFileRelativeUrl 下载相对地址
     *                         （我们从服务器端获取到的数据都是相对的地址）例如： "filepath": "/movie/20180511/1526028508.txt"
     */
    public void downloadFile(Context context, String fileUrl, String destFileDir,
                             final String destFileName, String mFileRelativeUrl, final int index) {
        String mDestFileName = destFileName + mFileRelativeUrl.substring(mFileRelativeUrl.lastIndexOf("."), mFileRelativeUrl.length());
        OkGo.<File>get(fileUrl).tag(context).execute(new FileCallback(destFileDir, mDestFileName) { //文件下载时指定下载的路径以及下载的文件的名称
            @Override
            public void onStart(Request<File, ? extends Request> request) {
                super.onStart(request);
                loadingDialog.show();
            }

            @Override
            public void onSuccess(com.lzy.okgo.model.Response<File> response) {
                ToastUtils.show(ModifyActivity.this, "下载成功,正在加载皮肤包");
                SelectTheme(destFileName, index);
                adapter.setSelectedPosition(index);
                adapter.notifyDataSetChanged();
                PreferenceUtils.setString(ModifyActivity.this, PreferenceValues.SELECTTHEME, index + "");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                loadingDialog.dismiss();
            }

            @Override
            public void onError(com.lzy.okgo.model.Response<File> response) {
                super.onError(response);
                Log.e("DownLoadFileUtils", "下载文件出错" + "DDDDD" + response.message());
                ToastUtils.show(ModifyActivity.this, "下载失败" + response.message());
            }

            @Override
            public void downloadProgress(Progress progress) {
                super.downloadProgress(progress);
                float dLProgress = progress.fraction;
                Log.e("DownLoadFileUtils", "文件下载的进度" + "DDDDD" + dLProgress);
            }
        });
    }

    /**
     * 加载主题
     *
     * @param SKIN_NAME
     */
    public void SelectTheme(String SKIN_NAME, final int index) {
        SKIN_DIR = Environment.getExternalStorageDirectory() + "/demain/skin/" + SKIN_NAME;
        skin = new File(SKIN_DIR);
        PreferenceUtils.setString(this, list.get(index).getFileName(), PreferenceValues.SKINNAME);
        SkinCompatManager.getInstance().loadSkin(list.get(index).getFileName(), null,
                CustomSDCardLoader.SKIN_LOADER_STRATEGY_SDCARD);
        Toast.makeText(ModifyActivity.this, "加载成功", Toast.LENGTH_SHORT).show();
        adapter.setSelectedPosition(index);
        adapter.notifyDataSetChanged();
        PreferenceUtils.setString(ModifyActivity.this, PreferenceValues.SELECTTHEME, index + "");
    }

    @OnClick({R.id.iv_class_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_class_back:
                finish();
                break;
        }
    }
}
